<template>
  <div>
    <!-- 开始页面 -->
    <motion
      v-if="!started"
      :initial="{ opacity: 0, y: 20 }"
      :animate="{ opacity: 1, y: 0 }"
      class="max-w-2xl mx-auto"
    >
      <div class="text-center space-y-6">
        <div class="relative">
          <motion
            :initial="{ scale: 0 }"
            :animate="{ scale: 1 }"
            :transition="{ duration: 0.5, ease: 'easeOut' }"
            :while-hover="{ scale: 1.05, transition: { duration: 0.3 } }"
            class="w-32 h-32 mx-auto mb-6 bg-gradient-to-br from-amber-400 to-orange-500 rounded-xl flex items-center justify-center shadow-lg"
          >
            <Boxes class="w-16 h-16 text-white" />
          </motion>
        </div>

        <h1 class="text-3xl font-bold bg-gradient-to-r from-amber-600 to-orange-600 bg-clip-text text-transparent">
          {{ $t('spatialReasoningTest.title') }}
        </h1>

        <p class="text-lg text-gray-600 max-w-md mx-auto">
          {{ $t('spatialReasoningTest.description') }}
        </p>

        <div class="bg-white/50 backdrop-blur-sm border border-gray-200 rounded-xl p-6 space-y-4">
          <h3 class="font-semibold flex items-center gap-2">
            <Box class="w-5 h-5 text-amber-500" />
            {{ $t('spatialReasoningTest.instructionsTitle') }}
          </h3>
          <div class="space-y-3 text-sm text-gray-500">
            <div class="flex items-start gap-2">
              <div class="w-2 h-2 bg-amber-500 rounded-full mt-2 flex-shrink-0"></div>
              <span>{{ $t('spatialReasoningTest.instructions.step1') }}</span>
            </div>
            <div class="flex items-start gap-2">
              <div class="w-2 h-2 bg-amber-500 rounded-full mt-2 flex-shrink-0"></div>
              <span>{{ $t('spatialReasoningTest.instructions.step2') }}</span>
            </div>
            <div class="flex items-start gap-2">
              <div class="w-2 h-2 bg-amber-500 rounded-full mt-2 flex-shrink-0"></div>
              <span>{{ $t('spatialReasoningTest.instructions.step3') }}</span>
            </div>
            <div class="flex items-start gap-2">
              <div class="w-2 h-2 bg-amber-500 rounded-full mt-2 flex-shrink-0"></div>
              <span>{{ $t('spatialReasoningTest.instructions.step4') }}</span>
            </div>
          </div>
        </div>

        <button
          @click="started = true"
          class="bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-600 hover:to-orange-600 text-white px-8 py-4 rounded-xl text-lg font-medium shadow-lg hover:shadow-xl transition-all duration-300 mx-auto flex items-center justify-center"
        >
          <Play class="w-5 h-5 mr-2" />
          {{ $t('spatialReasoningTest.startTest') }}
        </button>
      </div>
    </motion>

    <!-- 测试完成页面 -->
    <div v-else-if="testCompleted && finalResult" class="max-w-2xl mx-auto space-y-6">
      <div class="bg-white border border-gray-200 rounded-xl overflow-hidden">
        <div class="p-6 text-center">
          <h2 class="text-xl font-bold flex items-center justify-center gap-2">
            <Boxes class="w-6 h-6 text-amber-500" />
            {{ $t('spatialReasoningTest.testCompletedTitle') }}
          </h2>
        </div>
        <div class="space-y-6 px-6 pb-6">
          <div class="text-center space-y-4">
            <div class="text-6xl font-bold text-indigo-600">
              {{ finalResult.score }}
            </div>
            <div class="text-xl font-semibold text-amber-600">
              {{ finalResult.details.split(' | ')[2]?.split(': ')[1] || $t('spatialReasoningTest.defaultRank') }}
            </div>
            <div class="text-lg">
              {{ $t('spatialReasoningTest.accuracyRate') }}: <span class="font-bold text-indigo-600">{{ Math.round((correctAnswersCount / answers.length) * 100) }}%</span>
            </div>
          </div>

          <div class="grid grid-cols-2 gap-4">
            <div class="text-center p-4 bg-gray-100 rounded-lg">
              <div class="text-2xl font-bold">{{ correctAnswersCount }}</div>
              <div class="text-sm text-gray-600">{{ $t('spatialReasoningTest.correctAnswers') }}</div>
            </div>
            <div class="text-center p-4 bg-gray-100 rounded-lg">
              <div class="text-2xl font-bold">{{ SPATIAL_PROBLEMS.length - correctAnswersCount }}</div>
              <div class="text-sm text-gray-600">{{ $t('spatialReasoningTest.incorrectAnswers') }}</div>
            </div>
          </div>

          <div class="space-y-2">
            <h3 class="font-semibold">{{ $t('spatialReasoningTest.detailedAnalysis') }}</h3>
            <div class="text-sm text-gray-600 space-y-1">
              <p>• {{ $t('spatialReasoningTest.rotationAbility') }}: {{ rotationCorrect }}/{{ rotationTotal }}</p>
              <p>• {{ $t('spatialReasoningTest.foldingComprehension') }}: {{ foldingCorrect }}/{{ foldingTotal }}</p>
              <p>• {{ $t('spatialReasoningTest.perspectiveThinking') }}: {{ perspectiveCorrect }}/{{ perspectiveTotal }}</p>
            </div>
          </div>

          <div class="flex gap-4">
            <button
              @click="resetTest"
              class="flex-1 border-2 border-gray-300 hover:border-amber-500 hover:bg-amber-50 hover:text-amber-700 transition-all duration-200 rounded-md py-2 flex items-center justify-center"
            >
              <RotateCw class="w-4 h-4 mr-2" />
              {{ $t('spatialReasoningTest.retest') }}
            </button>
            <button
              @click="handleSaveResult"
              class="flex-1 bg-gradient-to-r from-amber-500 to-orange-500 text-white hover:from-amber-600 hover:to-orange-600 shadow-md hover:shadow-lg transition-all duration-200 rounded-md py-2"
            >
              {{ $t('spatialReasoningTest.saveResult') }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 测试中页面 -->
    <div v-else-if="currentProblem < SPATIAL_PROBLEMS.length" class="max-w-4xl mx-auto space-y-6">
      <!-- Header -->
      <div class="flex items-center justify-between">
        <div class="flex items-center gap-4">
          <span class="bg-gray-100 text-gray-700 border border-gray-300 rounded-md px-2 py-1 text-sm flex items-center gap-1">
            <Boxes class="w-3 h-3" />
            {{ $t('spatialReasoningTest.headerBadge') }}
          </span>
          <span class="text-sm text-gray-500">
            {{ $t('spatialReasoningTest.questionProgress', { current: currentProblem + 1, total: SPATIAL_PROBLEMS.length }) }}
          </span>
        </div>
        <div class="flex items-center gap-4">
          <span class="bg-gray-100 text-gray-700 border border-gray-300 rounded-md px-2 py-1 text-sm flex items-center gap-1">
            ⏰ {{ formatTime(timeLeft) }}
          </span>
          <button
            @click="skipProblem"
            class="border border-gray-300 rounded-md px-3 py-1 text-sm flex items-center gap-1 hover:bg-gray-50 transition-colors"
          >
            <SkipForward class="w-3 h-3" />
            {{ $t('spatialReasoningTest.skip') }}
          </button>
        </div>
      </div>

      <!-- Progress Bars -->
      <div class="space-y-2">
        <div class="flex justify-between text-sm">
          <span>{{ $t('spatialReasoningTest.progress') }}</span>
          <span>{{ Math.round(progress) }}%</span>
        </div>
        <div class="w-full bg-gray-200 rounded-full h-2">
          <div
            class="bg-indigo-600 h-2 rounded-full transition-all duration-300"
            :style="{ width: `${progress}%` }"
          ></div>
        </div>

        <div class="flex justify-between text-sm">
          <span>{{ $t('spatialReasoningTest.timeRemaining') }}</span>
          <span :class="{ 'text-red-500': timeLeft < 60 }">
            {{ formatTime(timeLeft) }}
          </span>
        </div>
        <div class="w-full bg-gray-200 rounded-full h-2" :class="{ 'bg-red-100': timeLeft < 60 }">
          <div
            class="h-2 rounded-full transition-all duration-300"
            :class="timeLeft < 60 ? 'bg-red-500' : 'bg-amber-500'"
            :style="{ width: `${timeProgress}%` }"
          ></div>
        </div>
      </div>

      <!-- Question -->
      <div class="bg-white border border-gray-200 rounded-xl overflow-hidden">
        <div class="p-6">
          <h2 class="flex items-center gap-2 font-bold text-lg">
            <RotateCw class="w-5 h-5 text-amber-500" />
            {{ problemTypeText }}
            <span class="ml-auto bg-gray-100 text-gray-700 border border-gray-300 rounded-md px-2 py-1 text-sm">
              {{ $t('spatialReasoningTest.difficulty', { level: SPATIAL_PROBLEMS[currentProblem].difficulty }) }}
            </span>
          </h2>
        </div>
        <div class="space-y-6 px-6 pb-6">
          <div class="text-center">
            <p class="text-lg mb-6">{{ SPATIAL_PROBLEMS[currentProblem].question }}</p>

            <!-- 模拟3D图形显示区域 -->
            <div class="bg-gradient-to-br from-gray-50 to-gray-100 rounded-xl p-8 mb-6">
              <div class="flex justify-center">
                <motion
                  class="text-6xl"
                  :initial="{ scale: 0 }"
                  :animate="{ scale: 1 }"
                  :transition="{ duration: 0.3, ease: 'easeOut' }"
                >
                  {{ problemIcon }}
                </motion>
              </div>
            </div>
          </div>

          <!-- Answer Options -->
          <div class="grid grid-cols-2 gap-4">
            <motion
              v-for="(shape, index) in SPATIAL_PROBLEMS[currentProblem].shapes"
              :key="index"
              :initial="{ opacity: 0, scale: 0.8 }"
              :animate="{ opacity: 1, scale: 1 }"
              :transition="{ delay: index * 0.1 }"
            >
              <button
                :class="[
                  'w-full h-20 text-lg font-medium transition-all duration-300 rounded-md border',
                  selectedAnswer === index
                    ? (index === SPATIAL_PROBLEMS[currentProblem].correct
                        ? 'bg-green-500 text-white border-green-500'
                        : 'bg-red-500 text-white border-red-500')
                    : showFeedback && index === SPATIAL_PROBLEMS[currentProblem].correct
                      ? 'bg-green-500 text-white border-green-500'
                      : 'border-gray-300 hover:border-amber-500 hover:bg-amber-50'
                ]"
                @click="handleAnswer(index)"
                :disabled="showFeedback"
              >
                <div class="flex items-center gap-3 justify-center">
                  <span class="text-2xl">{{ shape }}</span>
                  <span>{{ String.fromCharCode(65 + index) }}</span>
                </div>
              </button>
            </motion>
          </div>

          <!-- Feedback -->
          <motion
            v-if="showFeedback"
            :initial="{ opacity: 0, y: 20 }"
            :animate="{ opacity: 1, y: 0 }"
            :exit="{ opacity: 0, y: -20 }"
            :class="[
              'text-center p-4 rounded-lg border',
              selectedAnswer === SPATIAL_PROBLEMS[currentProblem].correct
                ? 'bg-green-50 text-green-700 border-green-200'
                : 'bg-red-50 text-red-700 border-red-200'
            ]"
          >
            {{ selectedAnswer === SPATIAL_PROBLEMS[currentProblem].correct
            ? $t('spatialReasoningTest.feedback.correct')
            : $t('spatialReasoningTest.feedback.incorrect', { answer: String.fromCharCode(65 + SPATIAL_PROBLEMS[currentProblem].correct), shape: SPATIAL_PROBLEMS[currentProblem].shapes[SPATIAL_PROBLEMS[currentProblem].correct] }) }}
          </motion>
        </div>
      </div>
    </div>

    <!-- 测试结束分析页面 -->
    <div v-else class="max-w-2xl mx-auto text-center">
      <motion
        :initial="{ opacity: 0, scale: 0.9 }"
        :animate="{ opacity: 1, scale: 1 }"
        class="space-y-6"
      >
        <div class="w-24 h-24 mx-auto bg-gradient-to-br from-green-400 to-emerald-500 rounded-full flex items-center justify-center">
          <Boxes class="w-12 h-12 text-white" />
        </div>
        <h2 class="text-2xl font-bold">{{ $t('spatialReasoningTest.analysis.title') }}</h2>
        <p class="text-gray-500">{{ $t('spatialReasoningTest.analysis.description') }}</p>
      </motion>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { Boxes, RotateCw, Box, Play, SkipForward } from 'lucide-vue-next';

const { t } = useI18n()

// 定义属性
const props = defineProps({
  onComplete: {
    type: Function,
    required: true
  }
})

// 问题数据
const SPATIAL_PROBLEMS = computed(() => Array.from({ length: 10 }, (_, i) => ({
  id: i + 1,
  type: t(`spatialReasoningTest.problems.q${i + 1}.type`),
  question: t(`spatialReasoningTest.problems.q${i + 1}.question`),
  shapes: Array.from({ length: 4 }, (__, j) => t(`spatialReasoningTest.problems.q${i + 1}.shapes.${j}`)),
  correct: parseInt(t(`spatialReasoningTest.problems.q${i + 1}.correct`)),
  difficulty: parseInt(t(`spatialReasoningTest.problems.q${i + 1}.difficulty`))
})))

// 状态定义
const started = ref(false)
const currentProblem = ref(0)
const answers = ref([])
const timeLeft = ref(420) // 7 minutes
const selectedAnswer = ref(null)
const showFeedback = ref(false)
const testCompleted = ref(false)
const finalResult = ref(null)
let timer = null

// 计算属性
const progress = computed(() => {
  return ((currentProblem.value + 1) / SPATIAL_PROBLEMS.value.length) * 100
})

const timeProgress = computed(() => {
  return (timeLeft.value / 420) * 100
})

const problemTypeText = computed(() => {
  const type = SPATIAL_PROBLEMS.value[currentProblem.value].type
  return t(`spatialReasoningTest.problemTypes.${type}`)
})

const problemIcon = computed(() => {
  const type = SPATIAL_PROBLEMS.value[currentProblem.value].type
  if (type === 'rotation') return '🔺'
  if (type === 'folding') return '📦'
  if (type === 'perspective') return '🎲'
  return ''
})

const correctAnswersCount = computed(() => {
  return answers.value.reduce((count, answer, index) => {
    return count + (answer === SPATIAL_PROBLEMS.value[index]?.correct ? 1 : 0)
  }, 0)
})

const rotationTotal = computed(() => {
  return SPATIAL_PROBLEMS.value.filter(p => p.type === 'rotation').length
})

const rotationCorrect = computed(() => {
  return answers.value.filter((answer, index) =>
    SPATIAL_PROBLEMS.value[index].type === 'rotation' && answer === SPATIAL_PROBLEMS.value[index].correct
  ).length
})

const foldingTotal = computed(() => {
  return SPATIAL_PROBLEMS.value.filter(p => p.type === 'folding').length
})

const foldingCorrect = computed(() => {
  return answers.value.filter((answer, index) =>
    SPATIAL_PROBLEMS.value[index].type === 'folding' && answer === SPATIAL_PROBLEMS.value[index].correct
  ).length
})

const perspectiveTotal = computed(() => {
  return SPATIAL_PROBLEMS.value.filter(p => p.type === 'perspective').length
})

const perspectiveCorrect = computed(() => {
  return answers.value.filter((answer, index) =>
    SPATIAL_PROBLEMS.value[index].type === 'perspective' && answer === SPATIAL_PROBLEMS.value[index].correct
  ).length
})

// 方法
const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
}

const handleAnswer = (answerIndex) => {
  selectedAnswer.value = answerIndex
  showFeedback.value = true

  setTimeout(() => {
    const newAnswers = [...answers.value, answerIndex]
    answers.value = newAnswers
    currentProblem.value = currentProblem.value + 1
    selectedAnswer.value = null
    showFeedback.value = false
  }, 1500)
}

const skipProblem = () => {
  const newAnswers = [...answers.value, -1] // -1 表示跳过
  answers.value = newAnswers
  currentProblem.value = currentProblem.value + 1
}

const handleTestComplete = () => {
  const correctAnswers = answers.value.reduce((count, answer, index) => {
    return count + (answer === SPATIAL_PROBLEMS.value[index]?.correct ? 1 : 0)
  }, 0)

  const score = Math.round((correctAnswers / SPATIAL_PROBLEMS.value.length) * 100)
  const accuracy = (correctAnswers / answers.value.length) * 100

  let levelKey = ''
  if (score >= 90) levelKey = 'spatialReasoningTest.ranks.master'
  else if (score >= 80) levelKey = 'spatialReasoningTest.ranks.expert'
  else if (score >= 70) levelKey = 'spatialReasoningTest.ranks.adept'
  else if (score >= 60) levelKey = 'spatialReasoningTest.ranks.novice'
  else levelKey = 'spatialReasoningTest.ranks.training'
  const level = t(levelKey)

  const result = {
    id: Date.now().toString(),
    testType: t('spatialReasoningTest.title'),
    score,
    completedAt: new Date(),
    duration: 420 - timeLeft.value,
    details: `${t('spatialReasoningTest.accuracyRate')}: ${accuracy.toFixed(1)}% | ${t('spatialReasoningTest.completedQuestions')}: ${answers.value.length}/${SPATIAL_PROBLEMS.value.length} | ${t('spatialReasoningTest.rank')}: ${level}`,
    difficulty: t('spatialReasoningTest.difficultyHard')
  }

  finalResult.value = result
  testCompleted.value = true

  // 停止计时器
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}

const handleSaveResult = () => {
  if (finalResult.value) {
    props.onComplete(finalResult.value)
  }
}

const resetTest = () => {
  started.value = false
  currentProblem.value = 0
  answers.value = []
  timeLeft.value = 420
  selectedAnswer.value = null
  showFeedback.value = false
  testCompleted.value = false
  finalResult.value = null

  // 停止计时器
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}

// 监听 started 状态变化
watch(started, (newValue) => {
  if (newValue) {
    // 开始测试时启动计时器
    timer = setInterval(() => {
      if (timeLeft.value > 0 && currentProblem.value < SPATIAL_PROBLEMS.value.length) {
        timeLeft.value = timeLeft.value - 1
      } else {
        handleTestComplete()
      }
    }, 1000)
  } else {
    // 停止测试时清除计时器
    if (timer) {
      clearInterval(timer)
      timer = null
    }
  }
})

// 监听 currentProblem 变化
watch(currentProblem, (newValue) => {
  if (newValue >= SPATIAL_PROBLEMS.value.length) {
    handleTestComplete()
  }
})

// 生命周期
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>
